/**
 * API 错误码定义
 * 统一管理所有接口的错误码和错误信息
 * 支持多语言错误消息
 */

import { LanguageType, DEFAULT_LANGUAGE } from '../config/languages';
import { ErrorMessageUtils } from '../locales/errorMessages';

// 错误码范围定义
export const ERROR_CODE_RANGES = {
  // 成功码
  SUCCESS: 200,
  
  // 客户端错误 (400-499)
  CLIENT_ERROR: {
    START: 400,
    END: 499
  },
  
  // 服务器错误 (500-599)
  SERVER_ERROR: {
    START: 500,
    END: 599
  },
  
  // 业务错误 (1000-1999)
  BUSINESS_ERROR: {
    START: 1000,
    END: 1999
  },
  
  // 认证授权错误 (2000-2999)
  AUTH_ERROR: {
    START: 2000,
    END: 2999
  },
  
  // 数据验证错误 (3000-3999)
  VALIDATION_ERROR: {
    START: 3000,
    END: 3999
  },
  
  // 数据库错误 (4000-4999)
  DATABASE_ERROR: {
    START: 4000,
    END: 4999
  },
  
  // 文件操作错误 (5000-5999)
  FILE_ERROR: {
    START: 5000,
    END: 5999
  },
  
  // 第三方服务错误 (6000-6999)
  EXTERNAL_SERVICE_ERROR: {
    START: 6000,
    END: 6999
  }
};

// 通用错误码
export const COMMON_ERROR_CODES = {
  // 成功
  SUCCESS: {
    code: 200,
    message: '操作成功'
  },
  
  // 客户端错误
  BAD_REQUEST: {
    code: 400,
    message: '请求参数错误'
  },
  UNAUTHORIZED: {
    code: 401,
    message: '未授权访问'
  },
  FORBIDDEN: {
    code: 403,
    message: '禁止访问'
  },
  NOT_FOUND: {
    code: 404,
    message: '资源不存在'
  },
  METHOD_NOT_ALLOWED: {
    code: 405,
    message: '请求方法不允许'
  },
  CONFLICT: {
    code: 409,
    message: '资源冲突'
  },
  UNPROCESSABLE_ENTITY: {
    code: 422,
    message: '请求无法处理'
  },
  TOO_MANY_REQUESTS: {
    code: 429,
    message: '请求过于频繁'
  },
  
  // 服务器错误
  INTERNAL_SERVER_ERROR: {
    code: 500,
    message: '服务器内部错误'
  },
  NOT_IMPLEMENTED: {
    code: 501,
    message: '功能未实现'
  },
  BAD_GATEWAY: {
    code: 502,
    message: '网关错误'
  },
  SERVICE_UNAVAILABLE: {
    code: 503,
    message: '服务不可用'
  },
  GATEWAY_TIMEOUT: {
    code: 504,
    message: '网关超时'
  }
};

// 业务错误码
export const BUSINESS_ERROR_CODES = {
  // 用户相关错误 (1000-1099)
  USER_NOT_FOUND: {
    code: 1000,
    message: '用户不存在'
  },
  USER_ALREADY_EXISTS: {
    code: 1001,
    message: '用户已存在'
  },
  USER_DISABLED: {
    code: 1002,
    message: '用户已被禁用'
  },
  USER_LOCKED: {
    code: 1003,
    message: '用户已被锁定'
  },
  USER_ALREADY_ACTIVE: {
    code: 1004,
    message: '用户已经是启用状态'
  },
  USER_ALREADY_INACTIVE: {
    code: 1005,
    message: '用户已经是禁用状态'
  },
  PASSWORD_INCORRECT: {
    code: 1006,
    message: '密码错误'
  },
  PASSWORD_EXPIRED: {
    code: 1007,
    message: '密码已过期'
  },
  ACCOUNT_EXPIRED: {
    code: 1008,
    message: '账户已过期'
  },
  LOGIN_FAILED: {
    code: 1009,
    message: '登录失败'
  },
  LOGOUT_FAILED: {
    code: 1010,
    message: '登出失败'
  },
  
  // 角色相关错误 (1100-1199)
  ROLE_NOT_FOUND: {
    code: 1100,
    message: '角色不存在'
  },
  ROLE_ALREADY_EXISTS: {
    code: 1101,
    message: '角色已存在'
  },
  ROLE_DISABLED: {
    code: 1102,
    message: '角色已被禁用'
  },
  ROLE_IN_USE: {
    code: 1103,
    message: '角色正在使用中，无法删除'
  },
  
  // 权限相关错误 (1200-1299)
  PERMISSION_NOT_FOUND: {
    code: 1200,
    message: '权限不存在'
  },
  PERMISSION_ALREADY_EXISTS: {
    code: 1201,
    message: '权限已存在'
  },
  PERMISSION_DENIED: {
    code: 1202,
    message: '权限不足'
  },
  PERMISSION_IN_USE: {
    code: 1203,
    message: '权限正在使用中，无法删除'
  },
  
  // 系统配置相关错误 (1300-1399)
  CONFIG_NOT_FOUND: {
    code: 1300,
    message: '配置不存在'
  },
  CONFIG_ALREADY_EXISTS: {
    code: 1301,
    message: '配置已存在'
  },
  CONFIG_INVALID: {
    code: 1302,
    message: '配置无效'
  },
  CONFIG_READ_ONLY: {
    code: 1303,
    message: '配置为只读，无法修改'
  },
  
  // 操作日志相关错误 (1400-1499)
  LOG_NOT_FOUND: {
    code: 1400,
    message: '日志不存在'
  },
  LOG_EXPORT_FAILED: {
    code: 1401,
    message: '日志导出失败'
  },
  LOG_CLEAR_FAILED: {
    code: 1402,
    message: '日志清理失败'
  }
};

// 认证授权错误码
export const AUTH_ERROR_CODES = {
  // 认证错误 (2000-2099)
  TOKEN_MISSING: {
    code: 2000,
    message: '访问令牌缺失'
  },
  TOKEN_INVALID: {
    code: 2001,
    message: '访问令牌无效'
  },
  TOKEN_EXPIRED: {
    code: 2002,
    message: '访问令牌已过期'
  },
  TOKEN_MALFORMED: {
    code: 2003,
    message: '访问令牌格式错误'
  },
  REFRESH_TOKEN_MISSING: {
    code: 2004,
    message: '刷新令牌缺失'
  },
  REFRESH_TOKEN_INVALID: {
    code: 2005,
    message: '刷新令牌无效'
  },
  REFRESH_TOKEN_EXPIRED: {
    code: 2006,
    message: '刷新令牌已过期'
  },
  SESSION_EXPIRED: {
    code: 2007,
    message: '会话已过期'
  },
  SESSION_INVALID: {
    code: 2008,
    message: '会话无效'
  },
  
  // 授权错误 (2100-2199)
  INSUFFICIENT_PERMISSIONS: {
    code: 2100,
    message: '权限不足'
  },
  ROLE_REQUIRED: {
    code: 2101,
    message: '需要特定角色'
  },
  PERMISSION_REQUIRED: {
    code: 2102,
    message: '需要特定权限'
  },
  ACCESS_DENIED: {
    code: 2103,
    message: '访问被拒绝'
  },
  IP_NOT_ALLOWED: {
    code: 2104,
    message: 'IP地址不被允许'
  },
  RATE_LIMIT_EXCEEDED: {
    code: 2105,
    message: '请求频率超限'
  }
};

// 数据验证错误码
export const VALIDATION_ERROR_CODES = {
  // 通用验证错误 (3000-3099)
  REQUIRED_FIELD_MISSING: {
    code: 3000,
    message: '必填字段缺失'
  },
  FIELD_TYPE_ERROR: {
    code: 3001,
    message: '字段类型错误'
  },
  FIELD_LENGTH_ERROR: {
    code: 3002,
    message: '字段长度错误'
  },
  FIELD_FORMAT_ERROR: {
    code: 3003,
    message: '字段格式错误'
  },
  FIELD_VALUE_ERROR: {
    code: 3004,
    message: '字段值错误'
  },
  
  // 用户数据验证错误 (3100-3199)
  USERNAME_INVALID: {
    code: 3100,
    message: '用户名格式无效'
  },
  EMAIL_INVALID: {
    code: 3101,
    message: '邮箱格式无效'
  },
  PASSWORD_TOO_WEAK: {
    code: 3102,
    message: '密码强度不足'
  },
  PHONE_INVALID: {
    code: 3103,
    message: '手机号格式无效'
  },
  
  // 业务数据验证错误 (3200-3299)
  DATA_INVALID: {
    code: 3200,
    message: '数据无效'
  },
  DATA_DUPLICATE: {
    code: 3201,
    message: '数据重复'
  },
  DATA_CONSTRAINT_VIOLATION: {
    code: 3202,
    message: '数据约束违反'
  },
  DATA_RELATIONSHIP_ERROR: {
    code: 3203,
    message: '数据关联错误'
  }
};

// 数据库错误码
export const DATABASE_ERROR_CODES = {
  // 连接错误 (4000-4099)
  CONNECTION_FAILED: {
    code: 4000,
    message: '数据库连接失败'
  },
  CONNECTION_TIMEOUT: {
    code: 4001,
    message: '数据库连接超时'
  },
  CONNECTION_LOST: {
    code: 4002,
    message: '数据库连接丢失'
  },
  
  // 查询错误 (4100-4199)
  QUERY_FAILED: {
    code: 4100,
    message: '数据库查询失败'
  },
  QUERY_TIMEOUT: {
    code: 4101,
    message: '数据库查询超时'
  },
  QUERY_SYNTAX_ERROR: {
    code: 4102,
    message: '数据库查询语法错误'
  },
  
  // 事务错误 (4200-4299)
  TRANSACTION_FAILED: {
    code: 4200,
    message: '数据库事务失败'
  },
  TRANSACTION_ROLLBACK: {
    code: 4201,
    message: '数据库事务回滚'
  },
  DEADLOCK_DETECTED: {
    code: 4202,
    message: '检测到死锁'
  },
  
  // 约束错误 (4300-4399)
  UNIQUE_CONSTRAINT_VIOLATION: {
    code: 4300,
    message: '唯一约束违反'
  },
  FOREIGN_KEY_CONSTRAINT_VIOLATION: {
    code: 4301,
    message: '外键约束违反'
  },
  NOT_NULL_CONSTRAINT_VIOLATION: {
    code: 4302,
    message: '非空约束违反'
  },
  CHECK_CONSTRAINT_VIOLATION: {
    code: 4303,
    message: '检查约束违反'
  }
};

// 文件操作错误码
export const FILE_ERROR_CODES = {
  // 文件不存在 (5000-5099)
  FILE_NOT_FOUND: {
    code: 5000,
    message: '文件不存在'
  },
  DIRECTORY_NOT_FOUND: {
    code: 5001,
    message: '目录不存在'
  },
  
  // 文件权限错误 (5100-5199)
  FILE_ACCESS_DENIED: {
    code: 5100,
    message: '文件访问被拒绝'
  },
  FILE_READ_ERROR: {
    code: 5101,
    message: '文件读取错误'
  },
  FILE_WRITE_ERROR: {
    code: 5102,
    message: '文件写入错误'
  },
  FILE_DELETE_ERROR: {
    code: 5103,
    message: '文件删除错误'
  },
  
  // 文件格式错误 (5200-5299)
  FILE_FORMAT_ERROR: {
    code: 5200,
    message: '文件格式错误'
  },
  FILE_SIZE_EXCEEDED: {
    code: 5201,
    message: '文件大小超限'
  },
  FILE_TYPE_NOT_ALLOWED: {
    code: 5202,
    message: '文件类型不允许'
  },
  
  // 文件上传错误 (5300-5399)
  UPLOAD_FAILED: {
    code: 5300,
    message: '文件上传失败'
  },
  UPLOAD_TIMEOUT: {
    code: 5301,
    message: '文件上传超时'
  },
  UPLOAD_INCOMPLETE: {
    code: 5302,
    message: '文件上传不完整'
  }
};

// 第三方服务错误码
export const EXTERNAL_SERVICE_ERROR_CODES = {
  // 网络错误 (6000-6099)
  NETWORK_ERROR: {
    code: 6000,
    message: '网络错误'
  },
  NETWORK_TIMEOUT: {
    code: 6001,
    message: '网络超时'
  },
  DNS_RESOLUTION_FAILED: {
    code: 6002,
    message: 'DNS解析失败'
  },
  
  // API调用错误 (6100-6199)
  API_CALL_FAILED: {
    code: 6100,
    message: 'API调用失败'
  },
  API_RESPONSE_INVALID: {
    code: 6101,
    message: 'API响应无效'
  },
  API_RATE_LIMIT_EXCEEDED: {
    code: 6102,
    message: 'API调用频率超限'
  },
  API_AUTHENTICATION_FAILED: {
    code: 6103,
    message: 'API认证失败'
  },
  
  // 邮件服务错误 (6200-6299)
  EMAIL_SEND_FAILED: {
    code: 6200,
    message: '邮件发送失败'
  },
  EMAIL_TEMPLATE_NOT_FOUND: {
    code: 6201,
    message: '邮件模板不存在'
  },
  EMAIL_RECIPIENT_INVALID: {
    code: 6202,
    message: '邮件收件人无效'
  },
  
  // 短信服务错误 (6300-6399)
  SMS_SEND_FAILED: {
    code: 6300,
    message: '短信发送失败'
  },
  SMS_TEMPLATE_NOT_FOUND: {
    code: 6301,
    message: '短信模板不存在'
  },
  SMS_RECIPIENT_INVALID: {
    code: 6302,
    message: '短信收件人无效'
  }
};

// 错误码映射表
export const ERROR_CODE_MAP: Record<string, { code: number; message: string }> = {
  ...COMMON_ERROR_CODES,
  ...BUSINESS_ERROR_CODES,
  ...AUTH_ERROR_CODES,
  ...VALIDATION_ERROR_CODES,
  ...DATABASE_ERROR_CODES,
  ...FILE_ERROR_CODES,
  ...EXTERNAL_SERVICE_ERROR_CODES
};

// 错误响应接口
export interface ErrorResponse {
  success: false;
  code: number;
  message: string;
  data?: any;
  timestamp?: string;
  path?: string;
  details?: any;
}

// 成功响应接口
export interface SuccessResponse<T = any> {
  success: true;
  code: number;
  message: string;
  data: T;
  timestamp?: string;
}

// 统一响应接口
export type ApiResponse<T = any> = SuccessResponse<T> | ErrorResponse;

/**
 * 错误码工具类
 */
export class ErrorCodeUtils {
  /**
   * 获取错误信息
   * @param code 错误码
   * @param customMessage 自定义错误信息
   * @param language 语言代码
   * @returns 错误信息对象
   */
  static getError(code: number, customMessage?: string, language: LanguageType = DEFAULT_LANGUAGE): ErrorResponse {
    // 使用多语言错误消息系统
    const message = customMessage || ErrorMessageUtils.getMessage(code, language);
    
    return {
      success: false,
      code,
      message,
      timestamp: new Date().toISOString()
    };
  }
  
  /**
   * 获取成功响应
   * @param data 响应数据
   * @param message 成功消息
   * @param language 语言代码
   * @returns 成功响应对象
   */
  static getSuccess<T>(data: T, message?: string, language: LanguageType = DEFAULT_LANGUAGE): SuccessResponse<T> {
    const successMessage = message || ErrorMessageUtils.getMessage(200, language);
    
    return {
      success: true,
      code: 200,
      message: successMessage,
      data,
      timestamp: new Date().toISOString()
    };
  }
  
  /**
   * 检查是否为有效的错误码
   * @param code 错误码
   * @returns 是否有效
   */
  static isValidErrorCode(code: number): boolean {
    return ErrorMessageUtils.hasErrorCode(code);
  }
  
  /**
   * 获取所有错误码
   * @returns 错误码列表
   */
  static getAllErrorCodes(): number[] {
    return ErrorMessageUtils.getAllErrorCodes();
  }
  
  /**
   * 根据错误类型获取错误码范围
   * @param errorType 错误类型
   * @returns 错误码范围
   */
  static getErrorCodeRange(errorType: keyof typeof ERROR_CODE_RANGES): { START: number; END: number } | number {
    return ERROR_CODE_RANGES[errorType] as { START: number; END: number } | number;
  }
}

// 导出所有错误码常量
export const ERROR_CODES = {
  COMMON: COMMON_ERROR_CODES,
  BUSINESS: BUSINESS_ERROR_CODES,
  AUTH: AUTH_ERROR_CODES,
  VALIDATION: VALIDATION_ERROR_CODES,
  DATABASE: DATABASE_ERROR_CODES,
  FILE: FILE_ERROR_CODES,
  EXTERNAL_SERVICE: EXTERNAL_SERVICE_ERROR_CODES
};

export default ErrorCodeUtils; 